<?php

namespace Admin\Controller;

class CategoryController extends CommonController
{
    public function _initialize()
    {
        parent::_initialize();
        // 刷新分类层级配置
        $data1['value'] = D('Category')->get_cat_level(1);
        $data2['value'] = D('Category')->get_cat_level(2);
        M('Config')->where("`name`='YTATA_CAT_LEVEL_QUESTION'")->save($data1);
        M('Config')->where("`name`='YTATA_CAT_LEVEL_ARTICLE'")->save($data2);
        if (!ytata_refresh_cache('config')) {
            $this->error('生成配置缓存文件失败！');
        }
    }

    // 问题分类
    public function cat_question()
    {
        $data = M("Category");
        //        $c_type = I('get.c_type', 1, 'intval');
        $c_type = 1;
        if (IS_AJAX) {
            $map['c_type']   = $c_type;
            $map['c_pid']    = I('get.c_pid', 0, 'intval');
            $list            = $data->where($map)->order('c_sort desc, c_id asc')->select();
            $list            = array_map(function ($item) {
                $item['c_pic']     = D('Category')->get_img_src($item['c_pic']);
                $item['editurl']   = RU('Category/cat_question_edit', array('c_id' => $item['c_id']));
                $item['deleteurl'] = RU('Category/delete', array('c_id' => $item['c_id']));
                return $item;
            }, $list);
            $ajax['status']  = 1;
            $ajax['content'] = $list;
            $this->ajaxReturn($ajax);
        } else {
            $map['c_type'] = $c_type;
            $map['c_pid']  = 0;
            $list          = $data->where($map)->order('c_sort desc, c_id asc')->select();
            $list          = array_map(function ($item) {
                $item['c_pic']     = D('Category')->get_img_src($item['c_pic']);
                $item['editurl']   = RU('Category/cat_bbs_edit', array('c_id' => $item['c_id']));
                $item['deleteurl'] = RU('Category/delete', array('c_id' => $item['c_id']));
                return $item;
            }, $list);
            $this->assign('c_type', $map['c_type']);
            $this->assign('list', $list);
            $this->display();
        }
    }

    /**
     * 添加问题分类
     */
    public function cat_question_add()
    {
        $data   = D("Category");
        $c_type = I('request.c_type');
        if (IS_POST) {
            if (!$data->create()) {
                $this->error($data->getError());
            } else {
                $data->c_sort = intval($data->c_sort);
                $data->add();
                $this->writeJS();
                $this->success('保存完成', I('post.url'));
            }
        } else {
            $map['c_type'] = $c_type;
            $map['c_pid']  = 0;
            $catlist       = $data->where($map)->order('c_sort desc, c_id asc')->select();
            $this->assign('catlist', $catlist);
            $this->assign('c_type', $c_type);
            $c_id = I('request.c_id', '', 'intval');
            if (!empty($c_id)) {
                $c_id_info = $data->where("c_id = " . $c_id)->limit(1)->find();
                $this->assign('c_pid_cn', $c_id_info['c_title']);
                $this->assign('c_pid', $c_id);
            }
            $this->display();
        }
    }

    //修改问题分类
    public function cat_question_edit()
    {
        if (IS_POST) {
            $data = D("Category");
            if (!$data->create()) {
                $this->error($data->getError());
            } else {
                $data->save();
                $this->writeJS();
                $this->success('保存完成', I('post.url'));
            }
        } else {
            $id = I('get.c_id', 0, 'intval');
            if ($id) {
                $data        = M("Category");
                $map['c_id'] = $id;
                $show        = $data->where($map)->limit(1)->find();
                $cat_info    = $data->where("c_id = " . $show['c_pid'])->limit(1)->find();
                $this->assign('c_pid_cn', $cat_info['c_title']);
                $this->assign('c_type', $show['c_type']);
                $this->assign('show', $show);
                $catmap['c_type'] = $show['c_type'];
                $catmap['c_pid']  = 0;
                $catlist          = $data->where($catmap)->order('c_sort desc, c_id asc')->select();
                $this->assign('catlist', $catlist);

                $this->display();
            } else {
                $this->error('非法请求');
            }
        }
    }

    //文章分类
    public function cat_article()
    {
        $data = M("Category");
        //        $c_type = I('get.c_type', 2, 'intval');
        $c_type = 2;
        if (IS_AJAX) {
            $map['c_type'] = $c_type;
            $map['c_pid']  = I('get.c_pid', 0, 'intval');
            $list          = $data->where($map)->order('c_sort desc, c_id asc')->select();
            if (!empty($list)) {
                foreach ($list as $key => $value) {
                    $list[$key]['addurl']    = RU('Category/cat_tag_add', array(
                        'c_id'   => $list[$key]['c_id'],
                        'c_type' => $list[$key]['c_type']
                    ));
                    $list[$key]['editurl']   = RU('Category/cat_tag_edit', array('c_id' => $list[$key]['c_id']));
                    $list[$key]['deleteurl'] = RU('Category/delete', array('c_id' => $list[$key]['c_id']));
                }
            }
            $ajax['status']  = 1;
            $ajax['content'] = $list;
            $this->ajaxReturn($ajax);
        } else {
            $map['c_type'] = $c_type;
            $map['c_pid']  = 0;
            $list          = $data->where($map)->order('c_sort desc, c_id asc')->select();
            $this->assign('c_type', $map['c_type']);
            $this->assign('list', $list);
            $this->display();
        }
    }

    // 添加文章分类
    public function cat_article_add()
    {
        $data   = D("Category");
        $c_type = I('request.c_type');
        if (IS_POST) {
            if (!$data->create()) {
                $this->error($data->getError());
            } else {
                $data->c_sort = intval($data->c_sort);
                $data->add();
                $this->success('保存完成', I('post.url'));
            }
        } else {
            $map['c_type'] = $c_type;
            $map['c_pid']  = 0;
            $catlist       = $data->where($map)->order('c_sort desc, c_id asc')->select();
            $this->assign('catlist', $catlist);
            $this->assign('c_type', $c_type);
            $c_id = I('request.c_id', '', 'intval');
            if (!empty($c_id)) {
                $c_id_info = $data->where("c_id = " . $c_id)->limit(1)->find();
                $this->assign('c_pid_cn', $c_id_info['c_title']);
                $this->assign('c_pid', $c_id);
            }
            $this->display();
        }
    }

    // 修改文章分类
    public function cat_article_edit()
    {
        if (IS_POST) {
            $data = D("Category");
            if (!$data->create()) {
                $this->error($data->getError());
            } else {
                $data->save();
                $this->success('保存完成', I('post.url'));
            }
        } else {
            $id = I('get.c_id', 0, 'intval');
            if ($id) {
                $data        = M("Category");
                $map['c_id'] = $id;
                $show        = $data->where($map)->limit(1)->find();
                $cat_info    = $data->where("c_id = " . $show['c_pid'])->limit(1)->find();
                $this->assign('c_pid_cn', $cat_info['c_title']);
                $this->assign('c_type', $show['c_type']);
                $this->assign('show', $show);
                $catmap['c_type'] = $show['c_type'];
                $catmap['c_pid']  = 0;
                $catlist          = $data->where($catmap)->order('c_sort desc, c_id asc')->select();
                $this->assign('catlist', $catlist);
                $this->display();
                //dump($show);
            } else {
                $this->error('非法请求');
            }
        }
    }

    // 删除任意分类
    public function delete()
    {
        $ids = I('request.c_id');
        if (!is_array($ids)) {
            $ids = array($ids);
        }
        $ids = implode(",", $ids);
        if ($ids && preg_match("/^(\d{1,10},)*(\d{1,10})$/", $ids)) {
            $data = M("Category");
            $s    = $data->delete($ids);
            $this->writeJS();
            $this->success("成功删除{$s}条数据");
        } else {
            $this->error('请选择要删除的信息！');
        }
    }

    // 保存所有分类
    public function allSave()
    {
        $c_id      = I('post.c_id');
        $c_title   = I('post.c_title');
        $c_sort    = I('post.c_sort');
        $add_type  = I('post.add_type');
        $add_pid   = I('post.add_pid');
        $add_title = I('post.add_title');
        $add_sort  = I('post.add_sort');
        $num       = 0;
        $data      = M("Category");
        if (is_array($c_id) && count($c_id) > 0) {
            foreach ($c_id as $k => $v) {
                unset($map);
                $map['c_id']    = intval($v);
                $map['c_title'] = trim($c_title[$k]);
                $map['c_sort']  = intval($c_sort[$k]);
                $data->save($map);
                $num++;

            }
        }
        if (is_array($add_pid) && count($add_pid) > 0) {
            foreach ($add_pid as $k => $v) {
                unset($map);
                $map['c_pid']   = intval($v);
                $map['c_type']  = intval($add_type[$k]);
                $map['c_title'] = trim($add_title[$k]);
                $map['c_sort']  = trim($add_sort[$k]);
                if (!empty($map['c_title'])) {
                    $data->add($map);
                    $num++;
                }
            }
        }
        if ($num > 0) {
            $this->writeJS();
            $this->success('成功保存' . $num . '个分类！');
        } else {
            $this->error('未保存任何分类！');
        }
    }

    /**
     * 讨论分类列表
     */
    public function cat_bbs()
    {
        $data = M("Category");
        //        $c_type = I('get.c_type', 3, 'intval');
        $c_type = 3;
        if (IS_AJAX) {
            $map['c_type']   = $c_type;
            $map['c_pid']    = I('get.c_pid', 0, 'intval');
            $list            = $data->where($map)->order('c_sort desc, c_id asc')->select();
            $list            = array_map(function ($item) {
                $item['editurl']   = RU('Category/cat_bbs_edit', array('c_id' => $item['c_id']));
                $item['deleteurl'] = RU('Category/delete', array('c_id' => $item['c_id']));
                return $item;
            }, $list);
            $ajax['status']  = 1;
            $ajax['content'] = $list;
            $this->ajaxReturn($ajax);
        } else {
            $map['c_type'] = $c_type;
            $map['c_pid']  = 0;
            $list          = $data->where($map)->order('c_sort desc, c_id asc')->select();
            $list          = array_map(function ($item) {
                $item['c_pic'] = D('Category')->get_img_src($item['c_pic']);
                return $item;
            }, $list);
            $this->assign('c_type', $map['c_type']);
            $this->assign('list', $list);
            $this->display();
        }
    }

    /**
     * 添加讨论分类
     */
    public function cat_bbs_add()
    {
        $Category = D("Category");
        $c_type   = I('request.c_type');

        if (IS_POST) {
            if (!$Category->create()) {
                $this->error($Category->getError());
            } else {
                $Category->c_sort = intval($Category->c_sort);
                $Category->add();
                $this->writeJS();
                $this->success('保存完成', I('post.url'));
            }
        } else {
            $data          = D('Category');
            $map['c_type'] = $c_type;
            $map['c_pid']  = 0;
            $catlist       = $data->where($map)->order('c_sort desc, c_id asc')->select();
            $this->assign('catlist', $catlist);
            $this->assign('c_type', $c_type);
            $c_id = I('request.c_id', '', 'intval');
            if (!empty($c_id)) {
                $c_id_info = $data->where("c_id = " . $c_id)->limit(1)->find();
                $this->assign('c_pid_cn', $c_id_info['c_title']);
                $this->assign('c_pid', $c_id);
            }
            $this->display();
        }
    }

    /**
     * 修改讨论分类
     */
    public function cat_bbs_edit()
    {
        if (IS_POST) {
            $data = D("Category");
            if (!$data->create()) {
                $this->error($data->getError());
            } else {
                $data->save();
                $this->writeJS();
                $this->success('保存完成', I('post.url'));
            }
        } else {
            $id = I('get.c_id', 0, 'intval');
            if ($id) {
                $data              = M("Category");
                $map['c_id']       = $id;
                $show              = $data->where($map)->limit(1)->find();
                $show['c_pic_src'] = D('Category')->get_img_src($show['c_pic']);
                $cat_info          = $data->where("c_id = " . $show['c_pid'])->limit(1)->find();
                $this->assign('c_pid_cn', $cat_info['c_title']);
                $this->assign('c_type', $show['c_type']);
                $this->assign('show', $show);
                $catmap['c_type'] = $show['c_type'];
                $catmap['c_pid']  = 0;
                $catlist          = $data->where($catmap)->order('c_sort desc, c_id asc')->select();
                $this->assign('catlist', $catlist);
                $this->display();
            } else {
                $this->error('非法请求');
            }
        }
    }

    /**
     * 生成分类JS
     */
    private function writeJS()
    {
        $data          = M("Category");
        $map['c_type'] = 1;
        $map['c_pid']  = 0;
        $arrayLevel    = 1;
        $list          = $data->where($map)->order('c_sort desc, c_id asc')->select();
        foreach ($list as $key => $value) {
            $parentarr[] = "\"" . $value['c_id'] . "," . $value['c_title'] . "\"";
        }
        $content = "//JavaScript Document 生成时间：" . date("Y-m-d  H:i:s") . "\n\n";
        $content .= "var ytata_cat_question_p=new Array(" . implode(',', $parentarr) . ");\n";
        $content .= "var ytata_cat_question  =new Array();\n";
        unset($map, $parentarr);
        foreach ($list as $val) {
            $map['c_pid'] = $val['c_id'];
            $list1        = $data->where($map)->order('c_sort desc, c_id asc')->select();
            if (!empty($list1)) {
                foreach ($list1 as $val1) {
                    $sarr[] = $val1['c_id'] . "," . $val1['c_title'];
                }
                $content    .= "ytata_cat_question[" . $val['c_id'] . "]=\"" . implode('|', $sarr) . "\"; \n";
                $arrayLevel = 2;
                unset($sarr);
            }
        }
        $content .= "var ytata_cat_question_level  ={$arrayLevel};\n";
        ///标签分类
        unset($map);
        $map['c_type'] = 2;
        $map['c_pid']  = 0;
        $arrayLevel    = 1;
        $list          = $data->where($map)->order('c_sort desc, c_id asc')->select();
        foreach ($list as $key => $value) {
            $parentarr[] = "\"" . $value['c_id'] . "," . $value['c_title'] . "\"";
        }
        $content .= "var ytata_cat_tag_p=new Array(" . implode(',', $parentarr) . ");\n";
        $content .= "var ytata_cat_tag  =new Array();\n";
        unset($map, $parentarr);
        foreach ($list as $val) {
            $map['c_pid'] = $val['c_id'];
            $list1        = $data->where($map)->order('c_sort desc, c_id asc')->select();
            if (!empty($list1)) {
                foreach ($list1 as $val1) {
                    $sarr[] = $val1['c_id'] . "," . $val1['c_title'];
                }
                $content    .= "ytata_cat_tag[" . $val['c_id'] . "]=\"" . implode('|', $sarr) . "\"; \n";
                $arrayLevel = 2;
                unset($sarr);
            }
        }
        $content .= "var ytata_cat_tag_level  ={$arrayLevel};\n";
        ////写入文件
        $path = "data/cache_cat.js";
        if (file_put_contents($path, $content)) {
            return true;
        } else {
            $this->error($path . '生成JS失败！');
        }
    }
}